package me.yobol.blog.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import me.yobol.blog.bean.PermissionBean;
import me.yobol.blog.dao.IPermissionDAO;

public class PermissionDAOImpl implements IPermissionDAO {
	
	private String sql;
	private String tableName = "tb_yobol_permission";
	//userIdFN = user_id Field Name
	private String userIdFN = "user_id",
				   roleIdFN = "role_id";
	private PreparedStatement ps;
	private ResultSet rs;

	@Override
	public void save(Connection ctn, PermissionBean ur) throws SQLException {
		sql = "insert into " + tableName + "("
				+ userIdFN + ","
				+ roleIdFN 
				+ ") values(?,?);";
		ps = ctn.prepareCall(sql);
		ps.setInt(1, ur.getUserId());
		ps.setInt(2, ur.getRoleId());
		ps.execute();
	}

	@Override
	public PermissionBean delete(Connection ctn, int userId)
			throws SQLException {
		//获取到要删除的用户记录，并封装到UserAndRoleBean中
		PermissionBean ur = getByUserId(ctn, userId);

		sql = "delete from " + tableName + " where " + userIdFN + " = " + userId;
		ps = ctn.prepareCall(sql);
		ps.execute();
		
		return ur;
	}

	@Override
	public void update(Connection ctn, int userId, int roleId)
			throws SQLException {
	}

	@Override
	public PermissionBean getByUserId(Connection ctn, int userId)
			throws SQLException {
		sql = "select * from " + tableName + " where " + userIdFN + " = " + userId;
		ps = ctn.prepareCall(sql);
		rs = ps.executeQuery();
			
		return wrapRs2Pb(rs);
	}

	@Override
	public List<PermissionBean> getByRoleId(Connection ctn, int roleId)
			throws SQLException {
		sql = "select * from " + tableName + " where " + roleIdFN + " = " + roleId;
		ps = ctn.prepareCall(sql);
		rs = ps.executeQuery();
		
		return wrapRs2PbList(rs);
	}
	
	/**
	 * Wraps a record pointed to by the current pointer in the ResultSet into the UserAndRoleBean
	 * 将ResultSet中当前指针指向的一条记录封装到UserAndRoleBean中
	 * 
	 * @param rs
	 * @return
	 * @throws SQLException 
	 */
	protected PermissionBean wrapRs2Pb(ResultSet rs) {
		PermissionBean ur = new PermissionBean();
		try {
			while(rs.next()){
				ur.setUserId(rs.getInt(userIdFN));
				ur.setRoleId(rs.getInt(roleIdFN));
				break;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return ur;
	}
	
	/**
	 * Wraps a record pointed to by the current pointer in the ResultSet into the UserAndRoleBean list
	 * 将ResultSet中当前指针指向的一条记录封装到UserAndRoleBean list中
	 * @param rs
	 * @return
	 * @throws SQLException
	 */
	protected List<PermissionBean> wrapRs2PbList(ResultSet rs) throws SQLException{
		List<PermissionBean> list = new ArrayList<>();
		PermissionBean ur = null;
		while(rs.next()){
			ur = new PermissionBean();
			
			ur.setUserId(rs.getInt(userIdFN));
			ur.setRoleId(rs.getInt(roleIdFN));
			
			list.add(ur);
		}
		return list;
	}

}
